<?php

namespace crmeb\jobs;


use app\common\repositories\activity\NewActivityRepository;
use app\common\repositories\store\coupon\StoreCouponRepository;
use app\common\repositories\store\coupon\StoreCouponUserRepository;
use app\common\repositories\user\UserRepository;
use crmeb\interfaces\JobInterface;
use think\facade\Log;

class SendNewActivityPeopleCouponJob implements JobInterface
{

    public function fire($job, $data)
    {
        if (!app()->make(NewActivityRepository::class)->exists($data['new_activity_id']))
            return $job->delete();
        $storeCouponRepository = app()->make(StoreCouponRepository::class);
        $coupon = $storeCouponRepository->getCoupon($data['coupon_id']);
        if($coupon ){
            if ($coupon->is_limited && 0 == $coupon->remain_count){
                Log::info('活动('.$data['new_activity_id'].')，优惠卷已被领完,');
            }
            try {
                $userList = app()->make(UserRepository::class)->getNotConsumed($data['new_activity_id'],$data['coupon_id']);
                foreach ($userList as $v){
                    if(count($v['coupon']) == 0){
                        $storeCouponRepository->sendCoupon($coupon, $v['uid'], StoreCouponUserRepository::SEND_TYPE_NEW,$data['new_activity_id']);
                    }
                }
            } catch (\Exception $e) {
                Log::info('活动('.$data['new_activity_id'].')自定发放优惠券:' . $e->getMessage());
            }
        }

        $job->delete();
    }

    public function failed($data)
    {
        // TODO: Implement failed() method.
    }
}
